package com.heima.behavior.service.impl;

import com.heima.behavior.service.BehaviorService;
import com.heima.common.constants.CacheConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class BehaviorServiceImpl implements BehaviorService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void likes(LikesBehaviorDto dto) {
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //1.确定数据结构 set key
        String key = CacheConstants.LIKES + dto.getArticleId();
        String userIdStr = user.getId().toString();
        if (dto.getOperation() == 0) {
            //2.判断是点赞 将数据保存
            stringRedisTemplate.opsForSet().add(key, userIdStr);
        } else {
            //3.取消点赞,将数据删除
            stringRedisTemplate.opsForSet().remove(key, userIdStr);
        }
    }
}
